package com.yang.exception;

import com.yang.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.ConversionFailedException;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    // 错误拦截方法
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        System.out.println("全局异常拦截");
        e.printStackTrace();
        return Result.error(StringUtils.hasLength(e.getMessage()) ? e.getMessage() : "操作失败");
    }

    // 处理参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleValidationException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();

        FieldError fieldError = bindingResult.getFieldError();
        String errorMessage = fieldError != null ? fieldError.getDefaultMessage() : "参数校验失败";
        return Result.error(errorMessage);
    }

    // 新增类型转换异常处理
    @ExceptionHandler(HttpMessageConversionException.class)
    public Result handleConversionException(HttpMessageConversionException ex) {
        log.error("类型转换异常: {}", ex.getMessage());
        // 针对BigDecimal类型转换错误
        if (ex.getCause() instanceof ConversionFailedException) {
            return Result.error("数值格式不正确，请使用小数点格式（如 9.99）");
        }
        return Result.error("请求参数类型错误");
    }

    @ExceptionHandler(ClientException.class)
    public Result handleClientException(ClientException ex) {
        return Result.error(ex.getMessage());
    }

}
